package ysq.xyg.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.StringUtil;
import org.apache.poi.ss.formula.functions.Match;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import ysq.weixin.client.WxApiClient;
import ysq.weixin.client.WxMemoryCacheClient;
import ysq.weixin.model.info.JSTicketShareResponse;
import ysq.weixin.util.MD5Util;
import ysq.weixin.util.weatherApi;
import ysq.xyg.model.*;
import ysq.xyg.model.info.ReturnEntity;
import ysq.xyg.model.info.ReturnInfo;
import ysq.xyg.model.info.WxAccountInfo;
import ysq.xyg.service.*;
import ysq.xyg.task.SendNoticeTask;
import ysq.xyg.util.BaseConstant;
import ysq.xyg.util.BaseUtil;
import ysq.xyg.util.DateUtil;
import ysq.xyg.util.ProProperties;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/6/23 0023.
 */
@Controller
@RequestMapping("/phone")
public class PhoneController extends BaseController {
    private static final Logger LOGGER= LoggerFactory.getLogger(PhoneController.class);
    @Resource
    private MemberService memberService;
    @Resource
    private ProductService productService;
    @Resource
    private ProductTypeService productTypeService;
    @Resource
    private RelayService relayService;
    @Resource
    private RelaySetService relaySetService;
    @Resource
    private DeviceService deviceService;
    @Resource
    private UserService userService;
    @Resource
    private SendNoticeTask sendNoticeTask;
    @Resource
    private WeatherService weatherService;
    private ModelAndView checkModelAndView;


    /**
     * 发送信息
     * */
    @RequestMapping(value = "/sendTask")
    public @ResponseBody
    JSONObject sendTask(String openid) throws MalformedURLException, UnsupportedEncodingException {
        ReturnInfo returnInfo=new ReturnInfo();
        JSONObject jsonObject=new JSONObject();
        sendNoticeTask.sendTask(openid);
        jsonObject.put("returnInfo",returnInfo);
        return jsonObject;
    }
    /**
     * 首页
     * */
    @RequestMapping("/index/{openid}")
    public ModelAndView index(HttpServletResponse response, HttpServletRequest request,@PathVariable String openid,String wxId) throws IOException {
        if(!check(openid, BaseConstant.WX_STATE_ONE)){
            return checkModelAndView;
        }
        Member member = memberService.selectByPrimaryKey(openid);
        List<Product> deviceList=productService.listLeft(new Product(BaseConstant.PRODUCT_TYPE_JCY,openid));
        if(deviceList!=null && deviceList.size()>0){
            for (int i=0;i<deviceList.size();i++){
                Product product=deviceList.get(i);
                Product d=null;
                try {
                    d=productService.selectData(product);
                }catch (Exception e){
                }
                if(d==null){
                    continue;
                }
                d.setDeviceType("2");
                if(d!=null&&d.getTime()!=null){
                    Date deviceDate=DateUtil.getSecondOneDate(d.getTime(),60*10);
                   if(deviceDate.getTime()>new Date().getTime()){
                    d.setDeviceType("1");
                   }
                }
                product.setNewProduct(d);
            }
        }
        List<Product> relayList=productService.listLeftK(new Product(BaseConstant.PRODUCT_TYPE_KZQ,openid));
        if(relayList!=null && relayList.size()>0){
            for (int i=0;i<relayList.size();i++){
                Product product=relayList.get(i);
                product.setDeviceType("2");
                if(product!=null&&product.getDeviceDate()!=null){
                    Date realyDate=DateUtil.getSecondOneDate(product.getDeviceDate(),60*10);
                    if(realyDate.getTime()>new Date().getTime()){
                        product.setDeviceType("1");
                    }
                }
            }
        }

        ModelAndView modelAndView=new ModelAndView("/mobile"+acceptTempletModel(wxId)+"/deviceList");
        modelAndView.addObject("openid",openid);
        modelAndView.addObject("wxId",wxId);
        modelAndView.addObject("wxAccountInfo",WxMemoryCacheClient.getSingleWxAccountInfo(wxId));
        modelAndView.addObject("deviceList",deviceList);
        modelAndView.addObject("relayList",relayList);
        modelAndView.addObject("jSTicketShareResponse",Share(request,wxId));
        if(member!=null && StringUtil.isNotEmpty(member.getNickName())){
            member.setNickName(BaseUtil.decodeBase64(member.getNickName()));
        }
        modelAndView.addObject("member",member);
        return modelAndView;
    }
    /**
     * wift设置
     * */
    @RequestMapping("/wift/{openid}")
    public ModelAndView wift(HttpServletResponse response, HttpServletRequest request,@PathVariable String openid,String wxId) throws IOException {
        if(!check(openid, BaseConstant.WX_STATE_ONE)){
            return checkModelAndView;
        }
        ModelAndView modelAndView=new ModelAndView("/mobile/wift");
        modelAndView.addObject("openid",openid);
        modelAndView.addObject("wxId",wxId);
        modelAndView.addObject("wxAccountInfo",WxMemoryCacheClient.getSingleWxAccountInfo(wxId));
        modelAndView.addObject("jSTicketShareResponse",Share(request,wxId));
        return modelAndView;
    }
    /**
     * 添加页面跳转链接
     * */
    @RequestMapping("/add/{openid}")
    public ModelAndView add(HttpServletResponse response, HttpServletRequest request,@PathVariable String openid,String deviceId,String type,String wxId) throws IOException {
        if(!check(openid, BaseConstant.WX_STATE_ONE)){
            return checkModelAndView;
        }
        List<ProductType> productTypeList=productTypeService.selectAll();
        ModelAndView modelAndView=new ModelAndView("/mobile/addProduct");
        modelAndView.addObject("openid",openid);
        modelAndView.addObject("deviceId",deviceId);
        modelAndView.addObject("type",type);
        modelAndView.addObject("wxId",wxId);
        modelAndView.addObject("wxAccountInfo",WxMemoryCacheClient.getSingleWxAccountInfo(wxId));
        modelAndView.addObject("productTypeList",productTypeList);
        modelAndView.addObject("jSTicketShareResponse",Share(request,wxId));
        return modelAndView;
    }
    /**
     * 添加页面跳转链接
     * */
    @RequestMapping("/addDesc/{openid}")
    public ModelAndView addDesc(HttpServletResponse response, HttpServletRequest request,@PathVariable String openid,String wxId) throws IOException {
        if(!check(openid, BaseConstant.WX_STATE_ONE)){
            return checkModelAndView;
        }
        ModelAndView modelAndView=new ModelAndView("/mobile/addProductDesc");
        modelAndView.addObject("openid",openid);
        modelAndView.addObject("wxId",wxId);
        modelAndView.addObject("wxAccountInfo",WxMemoryCacheClient.getSingleWxAccountInfo(wxId));
        modelAndView.addObject("jSTicketShareResponse",Share(request,wxId));
        return modelAndView;
    }

    /**
     * 添加页面跳转链接
     * */
    @RequestMapping("/addProductweixin/{openid}")
    public ModelAndView addProductweixin(HttpServletResponse response, HttpServletRequest request,@PathVariable String openid,String wxId) throws IOException {
        if(!check(openid, BaseConstant.WX_STATE_ONE)){
            return checkModelAndView;
        }
        List<ProductType> productTypeList=productTypeService.selectAll();
        ModelAndView modelAndView=new ModelAndView("/mobile/addProductweixin");
        modelAndView.addObject("wxId",wxId);
        modelAndView.addObject("wxAccountInfo",WxMemoryCacheClient.getSingleWxAccountInfo(wxId));
        modelAndView.addObject("openid",openid);
        modelAndView.addObject("jSTicketShareResponse",Share(request,wxId));
        return modelAndView;
    }
    /**
     * 设备添加
     * */
    @RequestMapping(value = "/addProduct/{openid}")
    public @ResponseBody
    JSONObject EvaluateList(@PathVariable String openid,Product product) throws MalformedURLException, UnsupportedEncodingException {
        ReturnInfo returnInfo=new ReturnInfo();
        JSONObject jsonObject=new JSONObject();
        if(product==null||StringUtil.isEmpty(product.getProductTypeId())||StringUtil.isEmpty(product.getDeviceId())||StringUtil.isEmpty(product.getName())){
            returnInfo=new ReturnInfo(BaseConstant.FAIL,"参数输入错误！");
            jsonObject.put("returnInfo",returnInfo);
            return jsonObject;
        }

        /*List<Product> productList=productService.list(new Product(product.getDeviceId()));
        if(productList!=null&&productList.size()>0){
            returnInfo=new ReturnInfo(BaseConstant.FAIL,"设备ID为["+product.getDeviceId()+"]已经被绑定！");
            jsonObject.put("returnInfo",returnInfo);
            return jsonObject;
        }*/
        if(BaseConstant.PRODUCT_TYPE_KZQ.equals(product.getProductTypeId())){
            List<Relay> relayList=relayService.list(new Relay(product.getDeviceId()));
            if(relayList==null||relayList.size()<=0){
                returnInfo=new ReturnInfo(BaseConstant.FAIL,"设备ID和设备类型不匹配！");
                jsonObject.put("returnInfo",returnInfo);
                return jsonObject;
            }
        }else{
            List<Device> deviceList=deviceService.list(new Device(product.getDeviceId()));
            if(deviceList==null||deviceList.size()<=0){
                returnInfo=new ReturnInfo(BaseConstant.FAIL,"设备ID和设备类型不匹配！");
                jsonObject.put("returnInfo",returnInfo);
                return jsonObject;
            }
        }
        product.setId(BaseUtil.uId());
        product.setCreateTime(new Date());
        product.setOpenid(openid);
        int id=productService.insert(product);
        if(id<=0){
            returnInfo=new ReturnInfo(BaseConstant.FAIL,"设备添加失败！");
        }
        jsonObject.put("returnInfo",returnInfo);
        return jsonObject;
    }
    /**
     * 检测仪页面跳转链接
     * */
    @RequestMapping("/device/{openid}")
    public ModelAndView device(HttpServletResponse response, HttpServletRequest request,@PathVariable String openid,String id,String wxId) throws IOException {
        if(!check(openid, BaseConstant.WX_STATE_ONE)){
            return checkModelAndView;
        }
        Product deviceProduct=new Product();
        deviceProduct.setId(id);
        List<Product> deviceList=productService.listLeft(deviceProduct);
        ModelAndView modelAndView=new ModelAndView("/mobile/deviceDesc");
        if(deviceList!=null && deviceList.size()>0){
            deviceProduct=deviceList.get(0);
            Product productData=null;
            try {
                productData=productService.selectData(new Product(deviceProduct.getDeviceId()));
            }catch (Exception e){
                modelAndView.setViewName("/mobile/dataError");
                modelAndView.addObject("openid",openid);
                modelAndView.addObject("wxId",wxId);
                modelAndView.addObject("title","设备编号："+deviceProduct.getDeviceId()+"错误，请查看是否没有数据！");
                modelAndView.addObject("wxAccountInfo",WxMemoryCacheClient.getSingleWxAccountInfo(wxId));
                modelAndView.addObject("jSTicketShareResponse",Share(request,wxId));
                return modelAndView;
            }
            productData=setTip(productData);
            deviceProduct.setNewProduct(productData);
            List<Weather> list=weatherService.list(new Weather(deviceProduct.getDeviceId()));
            if(list!=null&&list.size()>0){
                modelAndView.addObject("pm25",list.get(0).getPm25());
                modelAndView.addObject("wendu",list.get(0).getT());
                modelAndView.addObject("weatherType",list.get(0).getW());
            }
        }
        modelAndView.addObject("openid",openid);
        modelAndView.addObject("id",id);
        modelAndView.addObject("wxId",wxId);
        modelAndView.addObject("wxAccountInfo",WxMemoryCacheClient.getSingleWxAccountInfo(wxId));
        modelAndView.addObject("deviceProduct",deviceProduct);
        modelAndView.addObject("jSTicketShareResponse",Share(request,wxId));
        return modelAndView;
    }
    /**
     * 检测仪展示
     * */
    @RequestMapping("/deviceShow/{id}")
    public ModelAndView deviceShow(HttpServletResponse response, HttpServletRequest request,@PathVariable String id) throws IOException {
        ModelAndView modelAndView=new ModelAndView("/mobile/deviceShowDesc");
        Product productData=null;
        try {
            productData=productService.selectData(new Product(id));
        }catch (Exception e){
            modelAndView.addObject("title","设备编号："+id+"错误，请查看是否没有数据！");
            return modelAndView;
        }
        Product deviceProduct=new Product();
        List<Device> deviceList=deviceService.list(new Device(id));
        if(deviceList!=null&&deviceList.size()>0){
            deviceProduct.setType(deviceList.get(0).getType());
            deviceProduct.setDeviceBat(deviceList.get(0).getBat());
        }
        deviceProduct.setDeviceId(id);
        productData=setTip(productData);
        deviceProduct.setNewProduct(productData);
        List<Weather> list=weatherService.list(new Weather(deviceProduct.getDeviceId()));
        if(list!=null&&list.size()>0){
            modelAndView.addObject("pm25",list.get(0).getPm25());
            modelAndView.addObject("wendu",list.get(0).getT());
            modelAndView.addObject("weatherType",list.get(0).getW());
        }
        modelAndView.addObject("id",id);
        modelAndView.addObject("deviceProduct",deviceProduct);
        return modelAndView;
    }
    /**
     * 设备城市修改
     * */
    @RequestMapping(value = "/updateCity")
    public @ResponseBody
    JSONObject updateCity(String city,int id) throws MalformedURLException, UnsupportedEncodingException {
        ReturnInfo returnInfo=new ReturnInfo();
        JSONObject jsonObject=new JSONObject();
        if(StringUtil.isEmpty(city)||id<=0){
            returnInfo=new ReturnInfo(BaseConstant.FAIL,"参数输入错误！");
            jsonObject.put("returnInfo",returnInfo);
            return jsonObject;
        }
        Device device=deviceService.selectByPrimaryKey(id);
        device.setNowCity(city);
        int ids=deviceService.updateByPrimaryKey(device);
        if(ids<=0){
            returnInfo=new ReturnInfo(BaseConstant.FAIL,"城市信息修改失败！");
        }
        jsonObject.put("returnInfo",returnInfo);
        return jsonObject;
    }

    /**
     * 控制器页面跳转链接
     * */
    @RequestMapping("/relay/{openid}")
    public ModelAndView relay(HttpServletResponse response, HttpServletRequest request,@PathVariable String openid,int relayEntityId,String wxId) throws IOException {
        if(!check(openid, BaseConstant.WX_STATE_ONE)){
            return checkModelAndView;
        }
        Relay relay=relayService.selectByPrimaryKey(relayEntityId);
        relay.setDeviceType("2");
        if(relay!=null&&relay.getTime()!=null){
            Date relayDate=DateUtil.getSecondOneDate(relay.getTime(),60*10);
            if(relayDate.getTime()>new Date().getTime()){
                relay.setDeviceType("1");
            }
        }
        ModelAndView modelAndView=null;
        if(StringUtil.isNotEmpty(relay.getType())){
            modelAndView=new ModelAndView("/mobile/relay"+relay.getType());
        }else{
            modelAndView=new ModelAndView("/mobile/relay");
        }
        modelAndView.addObject("openid",openid);
        modelAndView.addObject("relayEntityId",relayEntityId);
        modelAndView.addObject("relay",relay);
        modelAndView.addObject("wxId",wxId);
        modelAndView.addObject("wxAccountInfo",WxMemoryCacheClient.getSingleWxAccountInfo(wxId));
        modelAndView.addObject("jSTicketShareResponse",Share(request,wxId));
        return modelAndView;
    }
    /**
     * 控制器操作修改
     * */
    @RequestMapping(value = "/updateRelay")
    public @ResponseBody
    JSONObject updateRelay(String type,int relayEntityId) throws MalformedURLException, UnsupportedEncodingException {
        ReturnInfo returnInfo=new ReturnInfo();
        JSONObject jsonObject=new JSONObject();
        if(StringUtil.isEmpty(type)||relayEntityId<=0){
            returnInfo=new ReturnInfo(BaseConstant.FAIL,"参数输入错误！");
            jsonObject.put("returnInfo",returnInfo);
            return jsonObject;
        }
        Relay relay=relayService.selectByPrimaryKey(relayEntityId);
        if(relay==null){
            returnInfo=new ReturnInfo(BaseConstant.FAIL,"relayEntityId输入错误！");
            jsonObject.put("returnInfo",returnInfo);
            return jsonObject;
        }
        if("1".equals(type)){
            //打开或关闭
            if("1".equals(relay.getPower())){
                relay.setPower("0");
            }else{
                relay.setPower("1");
            }
        }else if("2".equals(type)){
            //上调档位
            if("1".equals(relay.getKm())){
                relay.setKm("2");
            }else if("2".equals(relay.getKm())){
                relay.setKm("3");
            }else if("3".equals(relay.getKm())){
                relay.setKm("4");
            }else if("4".equals(relay.getKm())){
                returnInfo=new ReturnInfo(BaseConstant.FAIL,"已经是最大档位了！");
                jsonObject.put("returnInfo",returnInfo);
                return jsonObject;
            }else{
                relay.setKm("1");
            }
        }else if("3".equals(type)){
            //手动或自动
            if("1".equals(relay.getAuto())){
                relay.setAuto("0");
            }else{
                relay.setAuto("1");
            }
        }else if("4".equals(type)){
            //下调档位
            if("2".equals(relay.getKm())){
                relay.setKm("1");
            }else if("3".equals(relay.getKm())){
                relay.setKm("2");
            }else if("4".equals(relay.getKm())){
                relay.setKm("3");
            }else if("1".equals(relay.getKm())){
                returnInfo=new ReturnInfo(BaseConstant.FAIL,"已经是最小档位了！");
                jsonObject.put("returnInfo",returnInfo);
                return jsonObject;
            }else{
                relay.setKm("1");
            }
        }else if("5".equals(type)){
            //KM1
            if("1".equals(relay.getKm1())){
                relay.setKm1("0");
            }else{
                relay.setKm1("1");
            }
        }else if("6".equals(type)){
            //KM2
            if("1".equals(relay.getKm2())){
                relay.setKm2("0");
            }else{
                relay.setKm2("1");
            }
        }
        int id=relayService.updateByPrimaryKey(relay);
        if(id<=0){
            returnInfo=new ReturnInfo(BaseConstant.FAIL,"操作失败！");
        }
        jsonObject.put("returnInfo",returnInfo);
        return jsonObject;
    }
    /**
     * 控制器详情页面跳转链接
     * */
    @RequestMapping("/relaySet/{openid}")
    public ModelAndView relaySet(HttpServletResponse response, HttpServletRequest request,@PathVariable String openid,String relayId,String relayEntityId,String wxId) throws IOException {
        if((!check(openid, BaseConstant.WX_STATE_ONE))||StringUtil.isEmpty(relayId)){
            return checkModelAndView;
        }
        List<RelaySet> relaySetList=relaySetService.list(new RelaySet(relayId));
        RelaySet relaySet=null;
        if(relaySetList!=null&&relaySetList.size()>0){
            relaySet=relaySetList.get(0);
        }

        ModelAndView modelAndView=null;
        if(StringUtil.isNotEmpty(relaySet.getType())){
            modelAndView=new ModelAndView("/mobile/relaySet"+relaySet.getType());
        }else{
            modelAndView=new ModelAndView("/mobile/relaySet");
        }
        modelAndView.addObject("relayEntityId",relayEntityId);
        modelAndView.addObject("openid",openid);
        modelAndView.addObject("wxId",wxId);
        modelAndView.addObject("wxAccountInfo",WxMemoryCacheClient.getSingleWxAccountInfo(wxId));
        modelAndView.addObject("relaySet",relaySet);
        modelAndView.addObject("jSTicketShareResponse",Share(request,wxId));
        return modelAndView;
    }
    /**
     * 控制器操作修改
     * */
    @RequestMapping(value = "/updateRelaySet")
    public @ResponseBody
    JSONObject updateRelaySet(RelaySet relaySet) throws MalformedURLException, UnsupportedEncodingException {
        ReturnInfo returnInfo=new ReturnInfo();
        JSONObject jsonObject=new JSONObject();
        if(relaySet==null){
            returnInfo=new ReturnInfo(BaseConstant.FAIL,"参数输入错误！");
            jsonObject.put("returnInfo",returnInfo);
            return jsonObject;
        }
        int id=relaySetService.updateByPrimaryKey(relaySet);
        if(id<=0){
            returnInfo=new ReturnInfo(BaseConstant.FAIL,"设置失败！");
        }
        jsonObject.put("returnInfo",returnInfo);
        return jsonObject;
    }

    /**
     * 最大报警值修改
     * */
    @RequestMapping(value = "/updateDeviceMaxValue")
    public @ResponseBody
    JSONObject updateDeviceMaxValue(String id,double maxSendValue) throws MalformedURLException, UnsupportedEncodingException {
        ReturnInfo returnInfo=new ReturnInfo();
        JSONObject jsonObject=new JSONObject();
        if(StringUtil.isEmpty(id)){
            returnInfo=new ReturnInfo(BaseConstant.FAIL,"参数输入错误！");
            jsonObject.put("returnInfo",returnInfo);
            return jsonObject;
        }
        Product product=productService.selectByPrimaryKey(id);
        if(product==null){
            returnInfo=new ReturnInfo(BaseConstant.FAIL,"没有匹配的设备！");
            jsonObject.put("returnInfo",returnInfo);
            return jsonObject;
        }
        product.setMaxSendValue(maxSendValue);
        int ids=productService.updateByPrimaryKey(product);
        if(ids<=0){
            returnInfo=new ReturnInfo(BaseConstant.FAIL,"设置失败！");
        }
        jsonObject.put("returnInfo",returnInfo);
        return jsonObject;
    }
    /**
     * 测试仪统计详情页面跳转链接
     * */
    @RequestMapping("/deviceStatistics/{openid}")
    public ModelAndView deviceStatistics(HttpServletResponse response, HttpServletRequest request,@PathVariable String openid,String deviceType,String deviceId,String id,String type,String code,String wxId) throws IOException {
        if((!check(openid, BaseConstant.WX_STATE_ONE))||StringUtil.isEmpty(id)){
            return checkModelAndView;
        }
        ModelAndView modelAndView=new ModelAndView("/mobile/deviceStatistics");
        Date newDate=new Date();
        List<String> dataList=new ArrayList<String>();
        List<Double> dayList=new ArrayList<Double>();
        if("day".equals(type)||StringUtil.isEmpty(type)){
            //天
            Product product=new Product();
            product.setDeviceId(deviceId);
            product.setStartDate(DateUtil.DateToStr(newDate,DateUtil.DATE_PATTERN)+" 00:00:00");
            product.setEndDate(DateUtil.DateToStr(newDate,DateUtil.DATE_PATTERN)+" 23:59:59");
            List<Product> dayAllList=productService.selectDataList(product);
            Date baseDate=DateUtil.getBeginDate(DateUtil.DateToStr(newDate,DateUtil.DATE_PATTERN));
            Date currentDate=DateUtil.strToDate(DateUtil.DATE_TIME_PATTERN,DateUtil.DateToStr(newDate,DateUtil.DATE_PATTERN+" "+DateUtil.DATE_HOUR)+":00:00");
            //获取今天24小时
            for(int i=0;i<24;i++){
                if(currentDate.getTime()>=DateUtil.getSecondOneDate(baseDate,60*60*i).getTime()){
                    dataList.add(i+1+"时");
                    dayList.add(reslutValue(dayAllList,DateUtil.getSecondOneDate(baseDate,60*60*i),DateUtil.getSecondOneDate(baseDate,60*60*(i+1)),code));
                }
            }
        }else if("month".equals(type)){
            //月
            Product product=new Product();
            product.setDeviceId(deviceId);
            product.setStartDate(DateUtil.DateToStr(newDate,DateUtil.DATE_YEARMONTH)+"-01 00:00:00");
            List<Product> dayAllList=productService.selectDataList(product);
            Date baseDate=DateUtil.strToDate(DateUtil.DATE_TIME_PATTERN,DateUtil.DateToStr(newDate,DateUtil.DATE_YEARMONTH)+"-01 00:00:00");
            Date currentDate=DateUtil.strToDate(DateUtil.DATE_TIME_PATTERN,DateUtil.DateToStr(newDate,DateUtil.DATE_PATTERN)+" 00:00:00");
            for(int i=0;i<31;i++){
                if(currentDate.getTime()>=DateUtil.getDateOfDate(baseDate,-i).getTime()){
                    dataList.add("第"+(i+1)+"天");
                    Date startTime=DateUtil.strToDate(DateUtil.DATE_TIME_PATTERN,DateUtil.DateToStr(DateUtil.getDateOfDate(baseDate,-i),DateUtil.DATE_PATTERN)+" 00:00:00");
                    Date endTime=DateUtil.strToDate(DateUtil.DATE_TIME_PATTERN,DateUtil.DateToStr(DateUtil.getDateOfDate(baseDate,-i),DateUtil.DATE_PATTERN)+" 23:59:59");
                    dayList.add(reslutValue(dayAllList,startTime,endTime,code));
                }
            }
        }else if("year".equals(type)){
            //周
            Product product=new Product();
            product.setDeviceId(deviceId);
            product.setStartDate(DateUtil.DateToStr(DateUtil.getDateOfDate(newDate,7),DateUtil.DATE_PATTERN)+" 00:00:00");
            product.setEndDate(DateUtil.DateToStr(DateUtil.getDateOfDate(newDate,0),DateUtil.DATE_PATTERN)+" 23:59:59");
            List<Product> dayAllList=productService.selectDataList(product);
            for(int i=0;i<7;i++){
                int z=7-i;
                String baseDate=DateUtil.DateToStr(DateUtil.getDateOfDate(newDate,z),DateUtil.DATE_PATTERN);
                dataList.add(baseDate);
                Date startTime=DateUtil.strToDate(DateUtil.DATE_TIME_PATTERN,baseDate+" 00:00:00");
                Date endTime=DateUtil.strToDate(DateUtil.DATE_TIME_PATTERN,baseDate+" 23:59:59");
                dayList.add(reslutValue(dayAllList,startTime,endTime,code));
            }
        }

        modelAndView.addObject("deviceType",deviceType);
        modelAndView.addObject("deviceId",deviceId);
        modelAndView.addObject("openid",openid);
        modelAndView.addObject("id",id);
        modelAndView.addObject("type",type);
        modelAndView.addObject("code",code);
        modelAndView.addObject("wxId",wxId);
        modelAndView.addObject("wxAccountInfo",WxMemoryCacheClient.getSingleWxAccountInfo(wxId));
        modelAndView.addObject("dayList",JSONArray.toJSONString(dayList));
        modelAndView.addObject("dataList",JSONArray.toJSONString(dataList));
        modelAndView.addObject("jSTicketShareResponse",Share(request,wxId));
        return modelAndView;
    }

    /**
     * 设备删除修改
     * */
    @RequestMapping(value = "/deleteDevice")
    public @ResponseBody
    JSONObject deleteDevice(String productId) throws MalformedURLException, UnsupportedEncodingException {
        ReturnInfo returnInfo=new ReturnInfo();
        JSONObject jsonObject=new JSONObject();
        if(productId==null){
            returnInfo=new ReturnInfo(BaseConstant.FAIL,"参数输入错误！");
            jsonObject.put("returnInfo",returnInfo);
            return jsonObject;
        }
        int id=productService.deleteByPrimaryKey(productId);
        if(id<=0){
            returnInfo=new ReturnInfo(BaseConstant.FAIL,"删除失败！");
        }
        jsonObject.put("returnInfo",returnInfo);
        return jsonObject;
    }



    public static Double reslutValue(List<Product> allList,Date startTime,Date endTime,String type){
        List<Product> currentList=new ArrayList<Product>();
        if(allList!=null && allList.size()>0){
            for (Product product:allList){
                if(product.getTime()!=null && product.getTime().getTime()>=startTime.getTime()  && product.getTime().getTime()<endTime.getTime()){
                    currentList.add(product);
                }
            }
        }
        Double r=0.0;
        int num=0;
        int t=0;
        if(currentList!=null && currentList.size()>0){
            for (Product product:currentList) {
                if("AQI".equalsIgnoreCase(type)){
                    if(StringUtil.isNotEmpty(product.getAqi())) {
                        int aqi = Integer.parseInt(product.getAqi());
                        num++;
                        r=r+aqi;
                    }
                }else if("PM2".equalsIgnoreCase(type)){
                    if(StringUtil.isNotEmpty(product.getPm2())) {
                        int pm2 = Integer.parseInt(product.getPm2());
                        num++;
                        r=r+pm2;
                    }
                }else if("PM1".equalsIgnoreCase(type)){
                    //PM1
                    if(StringUtil.isNotEmpty(product.getPm1())) {
                        int pm1 = Integer.parseInt(product.getPm1());
                        num++;
                        r=r+pm1;
                    }
                }else if("PM10".equalsIgnoreCase(type)){
                    //PM10
                    if(StringUtil.isNotEmpty(product.getPm10())){
                        int pm10=Integer.parseInt(product.getPm10());
                        num++;
                        r=r+pm10;
                    }
                }else if("HCHO".equalsIgnoreCase(type)){
                    //hcho
                    if(StringUtil.isNotEmpty(product.getHcho())){
                        Double hcho=Double.parseDouble(product.getHcho());
                        num++;
                        r=r+hcho;
                        t=1;
                    }
                }else if("O2".equalsIgnoreCase(type)){
                    //o2
                    if(StringUtil.isNotEmpty(product.getO2())){
                        Double o2=Double.parseDouble(product.getO2());
                        num++;
                        r=r+o2;
                        t=1;
                    }
                }else if("CO2".equalsIgnoreCase(type)){
                    //co2
                    if(StringUtil.isNotEmpty(product.getCo2())){
                        int co2=Integer.parseInt(product.getCo2());
                        num++;
                        r=r+co2;
                    }
                }else if("temp".equalsIgnoreCase(type)){
                    //temp
                    if(StringUtil.isNotEmpty(product.getTemr())){
                        int temr=Integer.parseInt(product.getTemr());
                        num++;
                        r=r+temr;
                    }
                }else if("HIM".equalsIgnoreCase(type)){
                    //hum
                    if(StringUtil.isNotEmpty(product.getHim())){
                        int him=Integer.parseInt(product.getHim());
                        num++;
                        r=r+him;
                    }
                }else if("voc".equalsIgnoreCase(type)){
                    //voc
                    if(StringUtil.isNotEmpty(product.getVoc())){
                        Double voc=Double.parseDouble(product.getVoc());
                        num++;
                        r=r+voc;
                        t=1;
                    }
                }else if("windSpeed".equalsIgnoreCase(type)){
                    //windSpeed
                    if(StringUtil.isNotEmpty(product.getWindSpeed())){
                        int windSpeed=Integer.parseInt(product.getWindSpeed());
                        num++;
                        r=r+windSpeed;
                    }
                }else if("windDirection".equalsIgnoreCase(type)){
                    //windDirection
                    if(StringUtil.isNotEmpty(product.getWindDirection())){
                        int windDirection=Integer.parseInt(product.getWindDirection());
                        num++;
                        r=r+windDirection;
                    }
                }else if("noise".equalsIgnoreCase(type)){
                    //noise
                    if(StringUtil.isNotEmpty(product.getNoise())){
                        int noise=Integer.parseInt(product.getNoise());
                        num++;
                        r=r+noise;
                    }
                }
            }
        }

        if(num>0){
            r=r/num;
            if(t>0){
                r = (double)Math.round(r*100)/100;
            }else{
                r= (double)Math.round(r);
            }
        }
        return r;
    }

    /**
     * 通用验证
     * */
    protected  boolean check(String openid, String state){
        if(StringUtil.isNotEmpty(openid)){
            Member member=memberService.selectByPrimaryKey(openid);
            if(member!=null){
                return true;
            }
        }
        checkModelAndView=new ModelAndView("redirect:"+ ProProperties.getInstance().getWxOauthURL(state));
        return false;
    }

    public static Product setTip(Product product){
        if(product!=null){
            //windSpeed
            if(StringUtil.isNotEmpty(product.getWindSpeed())){
                int windSpeed=Integer.parseInt(product.getWindSpeed());
                if(windSpeed>=0 && windSpeed<50){
                    product.setWindSpeedTip("优秀");
                    product.setWindSpeedColor("#6BCD07");
                }else if(windSpeed>=50 && windSpeed<100){
                    product.setWindSpeedTip("良好");
                    product.setWindSpeedColor("#FBD029");
                }else if(windSpeed>=100 && windSpeed<150){
                    product.setWindSpeedTip("轻度污染");
                    product.setWindSpeedColor("#FE8800");
                }else if(windSpeed>=150 && windSpeed<200){
                    product.setWindSpeedTip("重度污染");
                    product.setWindSpeedColor("#970454");
                }else if(windSpeed>=300){
                    product.setWindSpeedTip("严重污染");
                    product.setWindSpeedColor("#62001E");
                }
            }
            //windDirection
            if(StringUtil.isNotEmpty(product.getWindDirection())){
                int windDirection=Integer.parseInt(product.getWindDirection());
                if(windDirection>=0 && windDirection<50){
                    product.setWindDirectionTip("优秀");
                    product.setWindDirectionColor("#6BCD07");
                }else if(windDirection>=50 && windDirection<100){
                    product.setWindDirectionTip("良好");
                    product.setWindDirectionColor("#FBD029");
                }else if(windDirection>=100 && windDirection<150){
                    product.setWindDirectionTip("轻度污染");
                    product.setWindDirectionColor("#FE8800");
                }else if(windDirection>=150 && windDirection<200){
                    product.setWindDirectionTip("重度污染");
                    product.setWindDirectionColor("#970454");
                }else if(windDirection>=300){
                    product.setWindDirectionTip("严重污染");
                    product.setWindDirectionColor("#62001E");
                }
            }
            //noise
            if(StringUtil.isNotEmpty(product.getNoise())){
                int noise=Integer.parseInt(product.getNoise());
                if(noise>=0 && noise<50){
                    product.setNoiseTip("优秀");
                    product.setNoiseColor("#6BCD07");
                }else if(noise>=50 && noise<100){
                    product.setNoiseTip("良好");
                    product.setNoiseColor("#FBD029");
                }else if(noise>=100 && noise<150){
                    product.setNoiseTip("轻度污染");
                    product.setNoiseColor("#FE8800");
                }else if(noise>=150 && noise<200){
                    product.setNoiseTip("重度污染");
                    product.setNoiseColor("#970454");
                }else if(noise>=300){
                    product.setNoiseTip("严重污染");
                    product.setNoiseColor("#62001E");
                }
            }
            //AQI
            if(StringUtil.isNotEmpty(product.getAqi())){
                int aqi=Integer.parseInt(product.getAqi());
                if(aqi>=0 && aqi<50){
                    product.setAqiTip("优秀");
                    product.setAqiColor("#6BCD07");
                }else if(aqi>=50 && aqi<100){
                    product.setAqiTip("良好");
                    product.setAqiColor("#FBD029");
                }else if(aqi>=100 && aqi<150){
                    product.setAqiTip("轻度污染");
                    product.setAqiColor("#FE8800");
                }else if(aqi>=150 && aqi<200){
                    product.setAqiTip("重度污染");
                    product.setAqiColor("#970454");
                }else if(aqi>=200){
                    product.setAqiTip("严重污染");
                    product.setAqiColor("#62001E");
                }
            }
            //PM2.5
            if(StringUtil.isNotEmpty(product.getPm2())){
                int pm2=Integer.parseInt(product.getPm2());
                if(pm2>=0 && pm2<35){
                    product.setPm2Tip("优");
                    product.setPm2Color("#6BCD07");
                }else if(pm2>=35 && pm2<75){
                    product.setPm2Tip("良");
                    product.setPm2Color("#F9F93A");
                }else if(pm2>=75 && pm2<115){
                    product.setPm2Tip("轻度污染");
                    product.setPm2Color("#F18741");
                }else if(pm2>=115 && pm2<150){
                    product.setPm2Tip("中度污染");
                    product.setPm2Color("#F93A3A");
                }else if(pm2>=150 && pm2<250){
                    product.setPm2Tip("重度污染");
                    product.setPm2Color("#C255DD");
                }else if(pm2>=250){
                    product.setPm2Tip("严重污染");
                    product.setPm2Color("#B32BD5");
                }
            }
            //PM1
            if(StringUtil.isNotEmpty(product.getPm1())){
                int pm1=Integer.parseInt(product.getPm1());
                if(pm1>=0 && pm1<35){
                    product.setPm1Tip("优");
                    product.setPm1Color("#6BCD07");
                }else if(pm1>=35 && pm1<75){
                    product.setPm1Tip("良");
                    product.setPm1Color("#F9F93A");
                }else if(pm1>=75 && pm1<115){
                    product.setPm1Tip("轻度污染");
                    product.setPm1Color("#F18741");
                }else if(pm1>=115 && pm1<150){
                    product.setPm1Tip("中度污染");
                    product.setPm1Color("#F93A3A");
                }else if(pm1>=150 && pm1<250){
                    product.setPm1Tip("重度污染");
                    product.setPm1Color("#C255DD");
                }else if(pm1>=250){
                    product.setPm1Tip("严重污染");
                    product.setPm1Color("#B32BD5");
                }
            }
            //PM10
            if(StringUtil.isNotEmpty(product.getPm10())){
                int pm10=Integer.parseInt(product.getPm10());
                if(pm10>=0 && pm10<35){
                    product.setPm10Tip("优");
                    product.setPm10Color("#6BCD07");
                }else if(pm10>=35 && pm10<75){
                    product.setPm10Tip("良");
                    product.setPm10Color("#F9F93A");
                }else if(pm10>=75 && pm10<115){
                    product.setPm10Tip("轻度污染");
                    product.setPm10Color("#F18741");
                }else if(pm10>=115 && pm10<150){
                    product.setPm10Tip("中度污染");
                    product.setPm10Color("#F93A3A");
                }else if(pm10>=150 && pm10<250){
                    product.setPm10Tip("重度污染");
                    product.setPm10Color("#C255DD");
                }else if(pm10>=250){
                    product.setPm10Tip("严重污染");
                    product.setPm10Color("#B32BD5");
                }
            }
            //hcho
            if(StringUtil.isNotEmpty(product.getHcho())){
                Double hcho=Double.parseDouble(product.getHcho());
                if(hcho>=0 && hcho<0.08){
                    product.setHchoTip("优秀");
                    product.setHchoColor("#6BCD07");
                }else if(hcho>=0.08 && hcho<0.15){
                    product.setHchoTip("良好");
                    product.setHchoColor("#F9F93A");
                }else if(hcho>=0.15 && hcho<0.2){
                    product.setHchoTip("轻度污染");
                    product.setHchoColor("#F18741");
                }else if(hcho>=0.2 && hcho<0.3){
                    product.setHchoTip("中度污染");
                    product.setHchoColor("#F93A3A");
                }else if(hcho>=0.3 && hcho<0.5){
                    product.setHchoTip("重度污染");
                    product.setHchoColor("#C255DD");
                }else if(hcho>=0.5){
                    product.setHchoTip("严重污染");
                    product.setHchoColor("#B32BD5");
                }
            }

            //o2
            if(StringUtil.isNotEmpty(product.getO2())){
                Double o2=Double.parseDouble(product.getO2());
                if(o2>=0 && o2<18){
                    product.setO2Tip("空气缺氧");
                    product.setO2Color("#C255DD");
                }else if(o2>=18 && o2<19){
                    product.setO2Tip("轻度浑浊");
                    product.setO2Color("#F9F93A");
                }else if(o2>=19){
                    product.setO2Tip("空气清新");
                    product.setO2Color("#6BCD07");
                }
            }
            //co2
            if(StringUtil.isNotEmpty(product.getCo2())){
                int co2=Integer.parseInt(product.getCo2());
                if(co2>=0 && co2<1000){
                    product.setCo2Tip("空气清新");
                    product.setCo2Color("#6BCD07");
                }else if(co2>=1000 && co2<2000){
                    product.setCo2Tip("轻度浑浊");
                    product.setCo2Color("#F9F93A");
                }else if(co2>=2000 && co2<5000){
                    product.setCo2Tip("空气浑浊");
                    product.setCo2Color("#F93A3A");
                }else if(co2>=5000){
                    product.setCo2Tip("空气缺氧");
                    product.setCo2Color("#C255DD");
                }
            }

            //temp
            if(StringUtil.isNotEmpty(product.getTemr())){
                int temr=Integer.parseInt(product.getTemr());
                if(temr<6){
                    product.setTemrTip("寒冷");
                    product.setTemrColor("#B32BD5");
                }else if(temr>=6 && temr<11){
                    product.setTemrTip("冷");
                    product.setTemrColor("#C255DD");

                }else if(temr>=11 && temr<15){
                    product.setTemrTip("偏冷");
                    product.setTemrColor("#F18741");

                }else if(temr>=15 && temr<18){
                    product.setTemrTip("凉");
                    product.setTemrColor("#F9F93A");
                }else if(temr>=18 && temr<28){
                    product.setTemrTip("舒适");
                    product.setTemrColor("#6BCD07");
                }else if(temr>=28){
                    product.setTemrTip("炎热");
                    product.setTemrColor("#F93A3A");
                }
            }
            //hum
            if(StringUtil.isNotEmpty(product.getHim())){
                int him=Integer.parseInt(product.getHim());
                if(him>=0 && him<40){
                    product.setHimTip("干燥");
                    product.setHimColor("#F93A3A");

                }else if(him>=40 && him<70){
                    product.setHimTip("舒适");
                    product.setHimColor("#6BCD07");
                }else if(him>=70){
                    product.setHimTip("潮湿");
                    product.setHimColor("#C255DD");
                }
            }
            //voc
            if(StringUtil.isNotEmpty(product.getVoc())){
                Double voc=Double.parseDouble(product.getVoc());
                if(voc>=0 && voc<0.2){
                    product.setVocTip("优秀");
                    product.setVocColor("#6BCD07");
                }else if(voc>=0.2 && voc<0.5){
                    product.setVocTip("良好");
                    product.setVocColor("#F9F93A");
                }else if(voc>=0.5 && voc<1.5){
                    product.setVocTip("轻度污染");
                    product.setVocColor("#F18741");
                }else if(voc>=1.5 && voc<2){
                    product.setVocTip("中度污染");
                    product.setVocColor("#F93A3A");
                }else if(voc>=2 && voc<3){
                    product.setVocTip("重度污染");
                    product.setVocColor("#C255DD");
                }else if(voc>=3){
                    product.setVocTip("严重污染");
                    product.setVocColor("#B32BD5");
                }
            }
        }
        return product;
    }


    /**
     * 绑定页面跳转链接
     * */
    @RequestMapping("/bind/{openid}")
    public ModelAndView bind(HttpServletResponse response, HttpServletRequest request,@PathVariable String openid,String wxId) throws IOException {
        if(!check(openid, BaseConstant.WX_STATE_ONE)){
            return checkModelAndView;
        }
        User user=new User();
        user.setOpenid(openid);
        List<User> userList=userService.listLeft(user);
        if(userList!=null&&userList.size()>0){
            user=userList.get(0);
        }
        ModelAndView modelAndView=new ModelAndView("/mobile/bindUser");
        modelAndView.addObject("openid",openid);
        modelAndView.addObject("user",user);
        modelAndView.addObject("wxId",wxId);
        modelAndView.addObject("wxAccountInfo",WxMemoryCacheClient.getSingleWxAccountInfo(wxId));
        modelAndView.addObject("jSTicketShareResponse",Share(request,wxId));
        return modelAndView;
    }

    /**
     * 通用分享可设置标题等
     * */
    protected JSTicketShareResponse Share(HttpServletRequest request, String fxTitle, String fxImgUrl, String fxDesc, String fxUrl, String wxId){
        WxAccountInfo wxAccountInfo= WxMemoryCacheClient.getSingleWxAccountInfo(wxId);
        String url= wxAccountInfo.getBaseURL()+request.getServletPath();
        //设置js分享
        JSTicketShareResponse jsTicketShareResponse = WxApiClient.getJSTicketShareResponse(url,wxId);
        jsTicketShareResponse.setFxTitle(fxTitle);
        jsTicketShareResponse.setFxImgUrl(fxImgUrl);
        jsTicketShareResponse.setFxDesc(fxDesc);
        jsTicketShareResponse.setFxUrl(fxUrl);
        jsTicketShareResponse.setAppid(wxAccountInfo.getAppid());
        return jsTicketShareResponse;
    }
    /**
     * 绑定账号
     * */
    @RequestMapping(value = "/bind")
    @Transactional
    public @ResponseBody
    JSONObject bindUser(String openid,String name,String password) throws MalformedURLException, UnsupportedEncodingException {
        ReturnInfo returnInfo=new ReturnInfo();
        JSONObject jsonObject=new JSONObject();
        if(StringUtil.isEmpty(openid)||StringUtil.isEmpty(name)||StringUtil.isEmpty(password)){
            returnInfo=new ReturnInfo(BaseConstant.FAIL,"参数输入错误！");
            jsonObject.put("returnInfo",returnInfo);
            return jsonObject;
        }
        User user=userService.selectByName(name);
        if(user == null || "".equals(user)){
            returnInfo=new ReturnInfo(BaseConstant.FAIL,"账号输入错误！");
            jsonObject.put("returnInfo",returnInfo);
            return jsonObject;
        }
        if(!(MD5Util.MD5Encode(password).equalsIgnoreCase(user.getUserPassword()))){
            returnInfo=new ReturnInfo(BaseConstant.FAIL,"账号和密码不匹配！");
            jsonObject.put("returnInfo",returnInfo);
            return jsonObject;
        }
        Product product=new Product();
        product.setOpenid(user.getOpenid());
        product.setNewOpenid(openid);
        productService.updateByOpenid(product);
        user.setOpenid(openid);
        userService.updateByPrimaryKey(user);
        jsonObject.put("returnInfo",returnInfo);
        return jsonObject;
    }

    /**
     * 通用分享可设置
     * */
    protected JSTicketShareResponse Share(HttpServletRequest request,String wxId){
        WxAccountInfo wxAccountInfo= WxMemoryCacheClient.getSingleWxAccountInfo(wxId);
        String url= wxAccountInfo.getBaseURL()+request.getServletPath();
        String c=request.getQueryString();
        if(StringUtil.isNotEmpty(c)){
            url=url+"?"+c;
        }
        //设置js分享
        JSTicketShareResponse jsTicketShareResponse = WxApiClient.getJSTicketShareResponse(url,wxId);
        jsTicketShareResponse.setFxTitle("分享标题");
        jsTicketShareResponse.setFxImgUrl(wxAccountInfo.getBaseURL()+"/mobile/img/5.png");
        jsTicketShareResponse.setFxDesc("分享描述");
        jsTicketShareResponse.setFxUrl(wxAccountInfo.getBaseURL()+"/weiXin/oauth/1?wxId="+wxAccountInfo.getId());
        jsTicketShareResponse.setAppid(wxAccountInfo.getAppid());
        return jsTicketShareResponse;
    }

}
